<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>C# 4.0 new features</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="C#, learn C#, new features, .NET, Mono, tutorial, programming language">
<meta name="description" content="This part of the C# tutorial covers new features of C# 4.0.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>C# 4.0 new features</h1>

<p>
In this part of the C# tutorial, we will talk about some of the
new features of the C# version 4.0. Microsoft introduced this
version of the C# in April 2010 with Visual Studio 2010. Mono C# 
compiler fully supported the new version by October 2010 with 
the release of Mono 2.8.
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script>

<p>
The C# 4.0 version brought the following new features to the language:
</p>

<ul>
  <li>Dynamic programming</li>
  <li>Named parameters</li>
  <li>Optional parameters</li>
  <li>Covariance and Contravariance</li>
</ul>


<h2>Dynamic programming</h2>

<p>
This new version of the C# language brought a new type <b class="keyword">dynamic</b>.
Once a variable is declared as having type dynamic, operations on these value 
are not done or verified at compile time, but instead happen entirely at runtime.
This is known also as <b class="keyword">duck typing</b>. The name of the concept refers 
to the duck test, which may be phrased as follows: "When I see a bird that walks like a duck 
and swims like a duck and quacks like a duck, I call that bird a duck". In other words,
we are concerned about what the object is doing rather than with the type of the object.
The dynamic type is used to simplify access to COM objects, IronPython and IronRuby
libraries and to the HTML DOM. 
</p>



<pre class="code">
using System;


public class Duck
{
    public void quack()
    {
        Console.WriteLine("Quaaaack");
    }
}

public class Person
{
    public void quack()
    {
        Console.WriteLine("Person imitates a duck");
    }
}


public class CSharpApp
{
    static void Main() 
    {
        Duck donald = new Duck();
        Person josh = new Person();
       
        InTheForest(donald);
        InTheForest(josh);
    }

    public static void InTheForest(dynamic duck)
    { 
        duck.quack();
    }
}
</pre>

<p>
In our example, we have two classes. The Duck class and the Person
class. Both have the quack() method. 
</p>

<pre class="explanation">
public static void InTheForest(dynamic duck)
{ 
    duck.quack();
}
</pre>

<p>
The InTheForest() method has a dynamic parameter. The type of the object
is not important; we are concerned about capabilities of the objects. 
If objects passed to the InTheForest() method can invoke the quack() method,
than we are fine. 
</p>

<pre>
$ dmcs ducktyping.cs
$ /usr/local/bin/mono ducktyping.exe 
Quaaaack
Person imitates a duck
</pre>

<p>
We compile and run the program. We use the Mono dmcs compiler, that is shipped
with the Mono 2.8 and supports the C# 4.0 profile. 
</p>

<h2>Named parameters</h2>

<p>
In earlier versions of the C# language, the arguments were provided in the order
in which they appeared in the method's signature. And the position in the
parameter list is important when evaluating a method. Named arguments enable us 
to specify the method parameters by their names. When specifying the named arguments,
the position of the parameter is not important anymore. 
</p>

<pre class="code">
using System;


public class CSharpApp
{
    static void Main() 
    {
        ShowMessage(name: "Jane", age: 17);
    }

    public static void ShowMessage(int age, string name)
    {
        Console.WriteLine("{0} is {1} years old", name, age);
    }
}
</pre>

<p>
A simple example with named arguments. 
</p>

<pre class="explanation">
ShowMessage(name: "Jane", age: 17);
</pre>

<p>
The parameter name is followed by the colon (:) character and
the value. The parameters may not be specified in order of the
method signature. 
</p>

<pre>
$ /usr/local/bin/mono named.exe 
Jane is 17 years old
</pre>

<p>
Output. 
</p>


<h2>Optional parameters</h2>

<p>
With C# 4.0 there are required parameters and optional parameters. 
Any call must provide arguments for all required parameters, but 
can omit arguments for optional parameters. Optional parameters are 
defined at the end of the parameter list, after any required parameters.
An optional parameter is created, when when a default value is specified 
for the parameters. 
</p>


<pre class="code">
using System;


public class CSharpApp
{
    static void Main() 
    {
        Power(4, 4);
        Power(5);
    }

    public static void Power(int x, int y=2)
    {
        int z = 1;

        for (int i=0; i&lt;y; i++)
        {
            z *= x;
        }

        Console.WriteLine(z);
    }
}
</pre>

<p>
An example for an optional argument. We have a Power() method. 
The method takes two parameters; the base and the exponent. 
If we do not specify the exponent, than the default 2 is used. 
</p>

<pre class="explanation">
public static void Power(int x, int y=2)
</pre>

<p>
In the method definition, we have a required x parameter and
the optional y parameter. The optional y has a default value.
</p>

<pre class="explanation">
Power(4, 4);
Power(5);
</pre>

<p>
When we call the Power() method, we can specify one or two 
parameters. 
</p>

<pre>
$ /usr/local/bin/mono optional.exe 
256
25
</pre>

<p>
Output of the example. 
</p>


<h2>Covariance &amp; contravariance</h2>

<p>
C# version 4.0 brings covariance for generics and delegate types. 
They were introduced because they bring flexibility to programming.
Within the type system of a programming language, covariance and 
contravariance refers to the ordering of types from narrower to wider 
and their interchangeability or equivalence in certain situations 
(such as parameters, generics, and return types). (wikipedia)
<p>

<p>
Types that are
</p>

<ul>
  <li>covariant: convert from wider (double) to narrower (float).</li>
  <li>contravariant: convert from narrower (float) to wider (double).</li>
  <li>invariant: are not able to convert (Null).</li>
</ul>


<pre class="code">
using System;


public class CSharpApp
{
    static void Main()
    {
        string[] langs = {"C#", "Python", "PHP", "Java"};
        object[] objs = langs;

        object o1 = objs[1];
        Console.WriteLine(o1);
    }
}
</pre>

<p>
Arrays are covariant from the beginning. 
</p>

<pre class="explanation">
string[] langs = {"C#", "Python", "PHP", "Java"};
</pre>

<p>
We have an array of string. 
</p>

<pre class="explanation">
object[] objs = langs;
</pre>

<p>
We assign a wider array of strings to a narrower object type.
</p>

<pre class="explanation">
object o1 = objs[1];
Console.WriteLine(o1);
</pre>

<p>
We get an item and print it to the console. 
</p>

<pre>
$ ./covariance.exe 
Python
</pre>

<p>
Output of the array covariance example. 
</p>

<hr class="btm">

<p>
In the following example, we have a covariance for generics. 
</p>

<pre class="code">
using System;
using System.Collections.Generic;


public class CSharpApp
{
    static void Main()
    {
        IEnumerable&lt;string&gt; strings = new List&lt;string&gt;() {"1", "3", "2", "5"};
        PrintAll(strings); 
    }

    static void PrintAll(IEnumerable&lt;object&gt; objects)
    {
        foreach (object o in objects)
        {
          System.Console.WriteLine(o);
        }
    }
}
</pre>

<p>
We have a generic list of strings. We call then the PrintAll() method, which
prints all the elements of the list. Note that the method parameter has a less
derived type parameter that our generic list. 
</p>

<pre>
$ /usr/local/bin/mono covariance2.exe 
1
3
2
5
</pre>

<p>
Output. 
</p>

<hr class="btm">

<p>
The following is an example for a covariance in delegates. 
</p>

<pre class="code">
using System;
using System.Collections.Generic;


public class CSharpApp
{
    static void Main()
    { 
        Action&lt;string&gt; del = ShowMessage; 
        del("Proximity alert");         
    }

    static void ShowMessage(object message) 
    { 
        Console.WriteLine(message);
    }
}
</pre>

<p>
We assign a method which has a narrower parameter type to a delegate,
which has a wider parameter type. 
</p>

<pre>
$ /usr/local/bin/mono contravariance.exe 
Proximity alert
</pre>

<p>
Output.
</p>

<p>
This part of the C# tutorial we have talked about new features of the C# 4.0.
</p>



<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified November 12, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>
